package com.ingenio.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.business.Localidad;
import com.ingenio.business.Sucursal;
import com.ingenio.dao.LocalidadAdapter;
import com.ingenio.dao.SucursalAdapter;

/**
 * Servlet implementation class DevolverPrecioServlet
 */
@WebServlet("/DevolverSucursales")
public class DevolverSucursalesLocalidadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevolverSucursalesLocalidadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer idLocalidad = Integer.parseInt(request.getParameter("idLocalidad"));
		LocalidadAdapter la = new LocalidadAdapter();
		SucursalAdapter sa = new SucursalAdapter();
		JSONObject json = new JSONObject();
		try {
			Localidad l = la.devolverLocalidad(idLocalidad);
			if (l != null){
				JSONArray jaLoc = new JSONArray();
				List<Sucursal> sucursales = sa.devolverSucursalesLocalidad(l);
				for (Sucursal s: sucursales){
					JSONObject jsucursales = new JSONObject();
					jsucursales.put("idSucursal", s.getIdSucursal());
					jsucursales.put("descSucursal", s.getDescSucursal());
					jaLoc.put(jsucursales);
				}
				json.put("sucursales", jaLoc);
			}else{
				json.put("error",true);
			}
			response.setContentType("application/json");
			response.getWriter().write(json.toString());	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
